package com.luzhikun.upload_3;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

/**
 * @Author Rookie Coder
 * @Description 文件上传
 * @Date
 **/
public class FileUpload_3 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 判断当前传回的数据是否为multpart/form-data
        if (!ServletFileUpload.isMultipartContent(req)) {
            throw new RuntimeException("当前请求不支持文件上传");

        }
        try {
            // 创建一个FileItem工厂
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // 设置临时文件的边界值，大于该值，上传文件会先保存在临时文件中，否则，上传文件会直接写入到内存中
            // 单位：字节，本例设置边界值为1M
            factory.setSizeThreshold(1024 * 1024 * 1);

            // 设置临时文件
            String tempPath = this.getServletContext().getRealPath("/temp");
            File temp = new File(tempPath);
            factory.setRepository(temp);

            // 创建文件上传核心组件
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 设置每一个items的头部字节编码，其可以解决文件名的中文乱码问题
            upload.setHeaderEncoding("UTF-8");
            // 设置单个上传文件的最大边界值为2M
            upload.setFileSizeMax(1024 * 1024 *2);
            // 设置一次上传所有文件的总和为 5 m
            upload.setSizeMax(1024 * 1024 * 5);

            // 解析请求，获取所有的item
            List<FileItem> fileItems = upload.parseRequest(req);

            // 遍历item
            Iterator<FileItem> iterator = fileItems.iterator();

            // 解析集合
            while (iterator.hasNext()) {
                FileItem next = iterator.next();
                // 判断next是否为表单普通项
                String fieldName = next.getFieldName();
                if (next.isFormField()) {
                    // 设置非文件表单项的字符集
                    String string = next.getString("UTF-8");
                    System.out.println(fieldName + "==" + string);
                } else {
                    // 如果是文件上传的
                    // 获取上传文件的原始名称
                    // 获取一个输出流
                    InputStream inputStream = next.getInputStream();
                    String path = this.getServletContext().getRealPath("/images");
                    System.out.println("------------------");
                    System.out.println(path);

                    // 获取当前系统时间
                    Calendar    now=new GregorianCalendar();
                    int year = now.get(Calendar.YEAR);
                    int month = now.get(Calendar.MONTH);
                    int day=now.get(Calendar.DAY_OF_MONTH);

                    path=path+"/"+year+"/"+(month+1)+"/"+day;
                    // 若目录不存在，则创建这个目录
                    File dirfile=new File(path);
                    if (!dirfile.exists()){
                        dirfile.mkdirs();
                    }

                    File descFile = new File(path, fieldName);
                    // 创建一个输出流
                    OutputStream os = new FileOutputStream(descFile);
                    int len = -1;
                    byte[] bytes = new byte[1024];
                    while ((len = inputStream.read(bytes)) != -1) {
                        os.write(bytes, 0, len);
                    }
                    // 关闭流
                    os.close();
                    inputStream.close();

                    // 删除临时文件
//                  fileItems.delete();

//                    next.delete();

                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }


    }
}
